package com.eastedu.superise.handler.question.handler.answer;

import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * The type Abstract ascii converter.
 *
 * @author ZhenZhong
 */
@Slf4j
public abstract class AbstractAsciiConverter implements AsciiConverter {

    @Override
    public int convert(String input) {
        if (Objects.isNull(input)) {
            return 0;
        }
        int i = doConvert(input);
        log.debug("Convert Answer: {} --> {}", input, i);
        return i;
    }

    /**
     * 校验答案是否是支持的累心
     *
     * @param actual the actual
     * @param offset the offset
     * @param end    the end
     * @return boolean
     */
    protected boolean validate(int actual, int offset, int end) {
        return actual >= offset && actual <= end;
    }

    /**
     * 转换操作
     *
     * @param input the input
     * @return int
     */
    protected int doConvert(String input) {
        int code = 0;
        int length = input.length();
        for (int i = 0; i < length; i++) {
            char c = input.charAt(i);
            if (c == ANSWER_SEPARATOR) {
                continue;
            }
            int temp = 1 << (c - getCharStartFlag());
            code += temp;
        }
        return code;
    }


    @Override
    public boolean isSupported(String input) {
        char[] chars = input.toCharArray();
        for (char c : chars) {
            if (c == ANSWER_SEPARATOR) {
                continue;
            }
            if (!validate(c, getCharStartFlag(), getCharEndFlag())) {
                return false;
//                addNotSupportedChar(c);
            }
        }
//        if (hasError()) {
//            return false;
//        }
        return true;
    }

    /**
     * 字符起始位置
     *
     * @return char start flag
     */
    protected abstract int getCharStartFlag();

    /**
     * 字符结束位置
     *
     * @return char end flag
     */
    protected abstract int getCharEndFlag();
}
